#define  _CRT_SECURE_NO_WARNINGS 1
#include <iostream>


 struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
 };
 
class Solution {
public:
    ListNode* detectCycle(ListNode* head) {
        set<ListNode*> s;
        ListNode* cur = head;
        while (cur) {
            auto it = s.find(cur);
            if (it == s.end()) {
                s.insert(cur);
            }
            else {
                return *it;

            }
            cur = cur->next;
        }
        return nullptr;
    }
};